(function () {

    // 获取显示页面数据 服务器分页 
    var serverData = {};
    serverData.key = '';
    var serverTable;
    jQuery(document).ready(function () {

        serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/news/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                    data: null,
                    defaultContent: ""// 排序
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {

                        var id=data.id
                        var operate ='<input type="checkbox" class="checkchild">';
                        return operate;

                    }
                },
                {
                    data: 'title',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 6) ? '<font title="'+data+'">'+data.substring(0,6)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'type',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 5) ? '<font title="'+data+'">'+data.substring(0,5)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'content',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'attachNumber',
                    render: function (data, type, full, meta) {
                    	var dOut;
                    	if(data==null){
                    		dOut='<td class="center" ><span class="badge label-pill label-primary">'+0+'</span></td>'
                    	}else{
                    		dOut='<td class="center" ><span class="badge label-pill label-primary">'+data+'</span></td>'
                    	}
                    	return dOut;
                    }
                    
                },{
                    data: 'nWatchNumber',
                    render: function (data, type, full, meta) {
                    	var dOut;
                    	if(data==null){
                    		dOut='<td class="center" ><span class="badge label-pill label-primary">'+0+'</span></td>'
                    	}else{
                    		dOut='<td class="center" ><span class="badge label-pill label-primary">'+data+'</span></td>'
                    	}
                    	return dOut;
                    }
                },
                {
                    data:'isPublished',
                    render: function (data, type, full, meta) {
                        var dOut;
                        if (data == 1) {
                            dOut = '<td class="center" ><span class="badge label-pill label-primary">已发布</span></td>';
                        }
                        else if (data == 0) {
                            dOut = '<td class="center" ><span class="badge label-pill label-danger">未发布</span></td>';
                        }
                        return dOut;
                    }

                },
                {
                    data: null,
                    render : function(data,
                                      type, full,
                                      meta) {
                    	if(data.isPublished == 1) {
                            return moment(data.updateTime).format("YYYY-MM-DD");
                        }
                    }

                }
                ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }

                serverTable.off('click', 'tr');
                serverTable.on('click', 'tr', function (event) {
                    event = event || window.event;
                    var target = event.target || event.scrElement;
                    var data = serverTable.row(this).data();

                    if (target.className.indexOf('fa-remove') != -1 || target.className.indexOf('delBtn') != -1) {

                        deleteModule(data);
                    }

                    if (target.className.indexOf('fa-pencil') != -1 || target.className.indexOf('editBtn') != -1) {

                        editModule(data);
                    }

                    return;
                });
            }
        });
        var deleteModule = function (data) {
            if (!data) return;
            $.springLemonDialog({
                content: '确认删除：' + data.title + '？',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    // index:0 确认 1：取消
                    // sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if (index == 0) {
                        var url =window.rootPath+ "/api/news/" + data.id;
                        jQuery.ajax({
                            url: encodeURI(url),
                            cache: false,
                            type: "delete",
                            dataType: "json",
                            success: function (data) {
                                serverTable.draw(false);
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }
            });
        };
        // 添加销售人员属性，弹窗清空
        jQuery('.addBtn').on('click', function () {
            jQuery('#id').val('');
            jQuery('#createTime').val('');
            jQuery('#title').val('');
            jQuery('#type').val('');
            jQuery('#content').val('');
            jQuery('#newsModal').modal('show');
        });
        // //编辑
        jQuery('.editBtn').on('click', function () {
            var selects=getSelect("#dataTable",1);
            if(selects.length>1){
                $.springLemonDialog({
                    content: '只能编辑一条记录',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                    }
                });
            }
            else if(selects.length==0){
                $.springLemonDialog({
                    content: '请选择要编辑的记录',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                    }
                });
            }else if(selects.length==1) {
            	if(selects[0].isPublished == 1){
            		$.springLemonDialog({
                        content: '信息已发布不可编辑！',// 确认文本
                        clickButton: function (sender, modal, index) {// 按钮事件处理
                            $(this).closeDialog(modal);
                        }
                    });
            		return;
            	}
                jQuery('#id').val(selects[0].id);
                jQuery('#title').val(selects[0].title);
                jQuery('#type').val(selects[0].type);
                jQuery('#content').val(selects[0].content);
                /*////获附件数量
                var newsId = jQuery("#id").val();
            	if(newsId!=''){
            		showANum(newsId,'公司信息附件','newANum');
            	}*/
                jQuery('#newsModal').modal('show');
            };
        });
        // //查看
        jQuery('.seeBtn').on('click', function () {
            var selects=getSelect("#dataTable",1);
            if(selects.length>1){
                $.springLemonDialog({
                    content: '只能查看一条记录',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                    }
                });
            }
            else if(selects.length==0){
                $.springLemonDialog({
                    content: '请选择要查看的记录',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                    }
                });
            }else if(selects.length==1) {
            	var id = selects[0].id;
            	var url = window.rootPath + "/ui/news/witch?id="+id;
            	jQuery.ajax({
                    type: 'get',
                    url:  encodeURI(url),
                    data: JSON.stringify(),
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                    	
                   }     
                });
            	jQuery('#id').val(selects[0].id);
                jQuery('#titleSee').val(selects[0].title);
                jQuery('#typeSee').val(selects[0].type);
                jQuery('#contentSee').val(selects[0].content);
                serverTable.draw();
                jQuery('#seeModal').modal('show');
            };
        });
        // 信息发布按钮
        jQuery('.publishedBtn').on('click', function () {
            var selects=getSelect("#dataTable",1);
            var url=window.rootPath+"/ui/news/publish";
            publishSelect(selects,url,serverTable)
        });
        var saveNews=function(state){
            var createTime = jQuery('#createTime').val();
            var title = jQuery('#title').val();
            var type = jQuery('#type').val();
            var content=jQuery('#content').val();
            var id=jQuery('#id').val();
            var url = window.rootPath + "/ui/news/save";
            // 判断是编辑还是新增
            if (id == "") {
                var d = {
                     "createTime":createTime,
                    "title":title,
                    "type": type,
                    "content": content,
                };

            } else {
                var d = {
                    "id" : id,
                    "title":title,
                    "type": type,
                    "content": content,

                };
            }
            jQuery.ajax({
                type: 'post',
                url:  encodeURI(url),
                data: JSON.stringify(d),
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                    if(state=='saveBtn'){
                    	jQuery('#newsModal').modal('hide');
                    	serverTable.draw();
                    }
                    else if(state=='upload'){
                        var newsId = data.news.id;
                        jQuery('#id').val(newsId);
                        fileUpload(newsId, "公司信息附件");
                        serverTable.draw();
                    }
                    
               }
                    
            });
        }

        jQuery(".saveBtn").on("click", function() {
            if (jQuery("#newsEditForm") && !jQuery("#newsEditForm").Validform({
                    tiptype : 3,
                    showAllError : true
                }).check(false)) {
                return;
            }
            saveNews('saveBtn');
        });

        // 查询
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#keyword').val();
            serverTable.draw();
        })
        // 撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#keyword').val('');
            serverData.key ='';
            serverTable.draw();
        });

        // ///删除/////
        jQuery('.delBtn').on('click', function () {
            var selects=getSelect("#dataTable",1);
            var url=window.rootPath+"/ui/news/del";
            delMessageSelect(selects,url,serverTable)
        });
        // 上传附件
        jQuery(".upload").on('click', function() {
            var newsId = jQuery("#id").val();
            if (newsId == '') {
                if (jQuery("#newsEditForm") && !jQuery("#newsEditForm").Validform({
                        tiptype : 3,
                        showAllError : true
                    }).check(false)) {
                    return;
                }
                ;
                $.springLemonDialog({
                    content : '将保存公司信息附件，是否继续',// 确认文本
                    clickButton : function(sender, modal, index) {// 按钮事件处理
                        if (index == 0) {
                            saveNews('upload');
                        }
                        $(this).closeDialog(modal);
                    }
                });
            } else {
                fileUpload(newsId, "公司信息附件");
            }
        });
        // 弹窗下载附件
        jQuery(".downList").on('click', function() {
        	var nId = jQuery("#id").val();
            filedown(nId, '公司信息附件','1');
        });
       
        
// 列表下载附件
        jQuery(".download").on('click', function() {
            var selects=getSelect("#dataTable",1);
            var nId=selects[0].id;
            filedown(nId, '公司信息附件',1);
        });
    });
    function delMessageSelect(selects,url,tableName){
    	if(selects.length==0){
    	       $.springLemonDialog({
    	         content: '请选择删除的记录',// 确认文本
    	         clickButton: function (sender, modal, index) {// 按钮事件处理
    	             $(this).closeDialog(modal);
    	         }
    	       }); 
    	   }else{
    		   var ids=selects[0].id;
    		   var operate ="0";
    		   for(var i=0;i<selects.length;i++){
    			   if(selects[i].isPublished =="1"){
    				   operate ="1";
    			   }
    			   
    		   }
    		   if(operate == "1"){
    			   $.springLemonDialog({
  	 		         content: '已发布信息不可删除！',// 确认文本
  	 		         clickButton: function (sender, modal, index) {// 按钮事件处理
  	 		             $(this).closeDialog(modal);
  	 		         }
  	 		   }); 
    		   }
    		   else{
    			   for(var i=1;i<selects.length;i++){
        			   ids += ',' + selects[i].id;  
        		   }
        		   var api=url+"?ids="+ids;
        		   $.springLemonDialog({
        		         content: '确认删除'+selects.length+'条记录？',// 确认文本
        		         clickButton: function (sender, modal, index) {// 按钮事件处理
        		        	 if (index == 0) {
        		        		 jQuery.ajax({
        		        			    url:encodeURI(api),
        		        	            cache:false,
        		        	            type :"get",
        		        	            dataType:"json",
        		        	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
        		        	            success:function(data){
        		        	            	serverTable.draw(false); 
        		        	            }
        		        	        });	
        		        	 }
        		             $(this).closeDialog(modal);
        		         }
        		       });
    		   }
    		     
    	   }
    	
    }
    function publishSelect(selects,url,tableName){
    	if(selects.length==0){
    	       $.springLemonDialog({
    	         content: '请选择要发布的信息',// 确认文本
    	         clickButton: function (sender, modal, index) {// 按钮事件处理
    	             $(this).closeDialog(modal);
    	         }
    	       }); 
    	   }else{
    		   var ids=selects[0].id;
    		   var operate ="0";
    		   for(var i=0;i<selects.length;i++){
    			   if(selects[i].isPublished =="1"){
    				   operate ="1";
    			   }
    			   
    		   }
    		   if(operate == "1"){
    	  			$.springLemonDialog({
    	 		         content: '不可重复发布信息！',// 确认文本
    	 		         clickButton: function (sender, modal, index) {// 按钮事件处理
    	 		             $(this).closeDialog(modal);
    	 		         }
    	 		   });  
    	  		 }
    		   else{
    			   for(var i=1;i<selects.length;i++){
        			   ids += ',' + selects[i].id;  
        		   }
        		   var api=url+"?ids="+ids;
        		   $.springLemonDialog({
        		         content: '确认发布'+selects.length+'条信息？',// 确认文本
        		         clickButton: function (sender, modal, index) {// 按钮事件处理
        		        	 if (index == 0) {
        		        			 jQuery.ajax({
        									url : encodeURI(api),
        									type : 'get',
        									dataType : 'json',
        									contentType : 'application/json;charset=utf-8',
        									success : function() {
        										serverTable.draw(false);
        									}
        								}); 
        		        		 	
        		        	 }
        		             $(this).closeDialog(modal);
        		         }
        		       });  
    		   }
    		     
    	   }
    	
    }
	   // /////列表中的全选
    $("#checkAll").click(function(){
    	var check = $(this).prop("checked");
        $(".checkchild").prop("checked", check);
	});
})();
